package com.btr.ivle;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.MenuItem;
import com.btr.ivle.R;
import com.btr.ivle.data.IVLEToken;
import com.btr.ivle.helper.DatabaseModule;
import com.btr.ivle.helper.DatabaseModuleItem;
import com.btr.ivle.helper.ModuleItemListAdapter;

public class ListModuleItemActivity extends SherlockActivity implements ActionBar.OnNavigationListener {
    public final static String EXTRA_MESSAGE_COURSECODE = "ListModuleItemActivity.COURSECODE";
    public final static String EXTRA_MESSAGE_COURSEID = "ListModuleItemActivity.COURSEID";
    public final static String EXTRA_MESSAGE_ID = "ListModuleItemActivity.ID";
    private int position;
    private ActionBar ab;
    
    public void onCreate(Bundle savedInstanceState) {
        setTheme(R.style.Theme_Sherlock_Light); //Used for theme switching in samples
        super.onCreate(savedInstanceState);
        setContentView(R.layout.moduledetail);
        
    	Intent intent = getIntent();
    	position = Integer.valueOf(intent.getStringExtra(MainActivity.EXTRA_MESSAGE));
    	try{
    		position = savedInstanceState.getInt("position");
    	}catch(Exception ex){
	    }
    	setActionBar();
    	
    }
    
	@Override
	public void onSaveInstanceState(Bundle savedInstanceState) {
	  super.onSaveInstanceState(savedInstanceState);
	  savedInstanceState.putInt("position", position);
	}

    public boolean onNavigationItemSelected(int itemPosition, long itemId) {
    	position = itemPosition;
    	DatabaseModule db = new DatabaseModule(this,IVLEToken.getUserID(),null,getResources().getInteger(R.integer.DBVersion));
        String table = IVLEToken.getUserID(); 
        String[] columns = new  String[] {db.colName, db.colCode}; 
        String orderBy = db.colCode + " ASC"; 
        Cursor c = db.getReadableDatabase().query(table, columns, 
        		null, null, null, null, orderBy, null);
        c.moveToPosition(itemPosition);
    	((TextView) findViewById(R.id.moduledetailTitle)).setText(c.getString(0));
    	setListView(c.getString(1));
    	c.close();
        db.getReadableDatabase().close();
        db.close();
        return true;
    }
    
    private void setActionBar(){
    	this.ab = getSupportActionBar();
        Context context = ab.getThemedContext();
        
    	final TextView titleTV = (TextView) findViewById(R.id.moduledetailTitle);
        String CourseCode = null;
        
    	ArrayAdapter<CharSequence> codeList = new ArrayAdapter<CharSequence>(context, R.layout.sherlock_spinner_item);

        DatabaseModule dbModule = new DatabaseModule(context,IVLEToken.getUserID(),null,getResources().getInteger(R.integer.DBVersion));
        String table = IVLEToken.getUserID(); 
        String[] columns = new  String[] {dbModule.colCode, dbModule.colName}; 
        String orderBy = dbModule.colCode + " ASC"; 
        Cursor c = dbModule.getReadableDatabase().query(table, columns, 
        		null, null, null, null, orderBy, null);
        c.moveToFirst();
        for  ( int  i =  0 ; i < c.getCount(); i++) { 
    		codeList.add(c.getString(0));
    		if(i==position){
    			CourseCode = c.getString(0);
    			titleTV.setText(c.getString(1));
    		}
	        c.moveToNext();
        }
        c.close();
        dbModule.getReadableDatabase().close();
        dbModule.close();

        codeList.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
        ab.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
        ab.setListNavigationCallbacks(codeList, this);
        ab.setDisplayShowHomeEnabled(false);
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setSelectedNavigationItem(position);
        
        setListView(CourseCode);
    }
    
    private void setListView(String code){
    	final String CourceCode = code;
    	ListView lv = (ListView) findViewById(R.id.list);
    	List<Map<String, String>> itemList = new ArrayList<Map<String, String>>();
		Map<String, String> map;
		
    	DatabaseModule dbModule = new DatabaseModule(this,IVLEToken.getUserID(),null,getResources().getInteger(R.integer.DBVersion)); 
		String table = IVLEToken.getUserID(); 
		String[] columns = new  String[] {dbModule.colWorkbins, dbModule.colForums, dbModule.colWebcasts, 
				dbModule.colGradebooks, dbModule.colWebLinks, dbModule.colID, dbModule.colNewAnnounce};
		String selection = dbModule.colCode + "=?";
		String[] selectionArgs = new  String[] {code};
		String orderBy = dbModule.colCode + " ASC"; 
		Cursor c = dbModule.getReadableDatabase().query(table, columns, 
				selection, selectionArgs, null, null, orderBy, null);
		
		c.moveToFirst();
		final int nWorkbin = c.getInt(0);
		final int nForum = c.getInt(1);
		final int nWebcast = c.getInt(2);
		final int nGradebook = c.getInt(3);
		final int nWeblink = c.getInt(4);
		final String CourseID = c.getString(5);
		final String unreadAnnouncement = c.getString(6);
		
		map = new HashMap<String, String>();
		map.put("item", "Announcement");
		map.put("unread", unreadAnnouncement);
		itemList.add(map);
		
		itemList.addAll(getItems(nWorkbin, "Workbin", code));
		itemList.addAll(getItems(nForum, "Forum", code));
		itemList.addAll(getItems(nWebcast, "Webcast", code));
		
		if(nGradebook>0){
			map = new HashMap<String, String>();
			map.put("item", "Gradebook");
			itemList.add(map);
		}
		if(nWeblink>0){
			map = new HashMap<String, String>();
			map.put("item", "Weblink");
			itemList.add(map);
		}	
		
		c.close();
		dbModule.getReadableDatabase().close();
		dbModule.close();
		
		final List<Map<String, String>> itemListFinal = itemList;
		ModuleItemListAdapter adapter = new ModuleItemListAdapter(this, itemList);
        lv.setAdapter(adapter);
        lv.setTextFilterEnabled(true);
        lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            	int n1 = 0, n2 = 0;
            	if(position == n1){
				  Intent intent = new Intent(ListModuleItemActivity.this, ListAnnouncementActivity.class);
				  intent.putExtra(EXTRA_MESSAGE_COURSECODE, CourceCode);
				  startActivityForResult(intent, 1);
            	}
            	n2 += nWorkbin;
            	if(position > n1 && position <= n2){
  				  Intent intent = new Intent(ListModuleItemActivity.this, ViewWorkbinActivity.class);
  				  intent.putExtra(EXTRA_MESSAGE_COURSECODE, CourceCode);
  				  intent.putExtra(EXTRA_MESSAGE_COURSEID, CourseID);
  				  intent.putExtra(EXTRA_MESSAGE_ID, itemListFinal.get(position).get("id"));
  				  startActivity(intent);
              	}
            	n1 = n2;
            	n2 += nForum;
            	if(position > n1 && position <= n2){
    				  Intent intent = new Intent(ListModuleItemActivity.this, ListForumPostActivity.class);
    				  intent.putExtra(EXTRA_MESSAGE_COURSECODE, CourceCode);
    				  intent.putExtra(EXTRA_MESSAGE_ID, itemListFinal.get(position).get("id"));
    				  startActivity(intent);
                }
            	n1 = n2;
            	n2 += nWebcast;
            	if(position > n1 && position <= n2){
	  				  Intent intent = new Intent(ListModuleItemActivity.this, ViewWebcastActivity.class);
	  				  intent.putExtra(EXTRA_MESSAGE_COURSECODE, CourceCode);
	  				  startActivity(intent);
            	}
            	n1 = n2;
            	n2 += nGradebook;
            	if(position > n1 && position <= n2){
	  				  Intent intent = new Intent(ListModuleItemActivity.this, ViewGradebookActivity.class);
	  				  intent.putExtra(EXTRA_MESSAGE_COURSECODE, CourceCode);
	  				  startActivity(intent);
            	}
            	n1 = n2;
            	n2 += nWeblink;
            	if(position > n1 && position <= n2){
	  				  Intent intent = new Intent(ListModuleItemActivity.this, ViewWeblinkActivity.class);
	  				  intent.putExtra(EXTRA_MESSAGE_COURSECODE, CourceCode);
	  				  startActivity(intent);
            	}
            }
          });
    }
    
    private List<Map<String, String>> getItems(int n, String item, String code){
    	List<Map<String, String>> list = new ArrayList<Map<String, String>>();
    	Map<String, String> map;
    	
    	DatabaseModuleItem dbModuleItem = new DatabaseModuleItem(this,IVLEToken.getUserID()+"_ModuleItem",null,getResources().getInteger(R.integer.DBVersion));
		String table = IVLEToken.getUserID()+"_ModuleItem"; 
        String[] columns = new  String[] {dbModuleItem.colName, dbModuleItem.colID, dbModuleItem.colBadgeTool}; 
        String selection = dbModuleItem.colType + "=? AND " + dbModuleItem.colCode + "=?";
		String[] selectionArgs = new  String[] {item, code};
        String orderBy = dbModuleItem.colName + " ASC";
        Cursor c = dbModuleItem.getReadableDatabase().query(table, columns, 
        		selection, selectionArgs, null, null, orderBy, null);
        c.moveToFirst();
        for  ( int  i =  0 ; i < c.getCount(); i++) { 
        	map = new HashMap<String, String>();
			map.put("item", item);
			map.put("name", c.getString(0));
			map.put("id", c.getString(1));
			map.put("unread", c.getString(2));
			list.add(map);
	        c.moveToNext();
        }
        c.close();
        dbModuleItem.getReadableDatabase().close();
        dbModuleItem.close();

    	return list;
    }

    @Override
    public boolean onOptionsItemSelected(final MenuItem item) 
    {
    	switch (item.getItemId()) {
        case android.R.id.home:
          super.onBackPressed();
    	}
          return true;
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent){
    	int newPosition = Integer.valueOf(intent.getStringExtra("position"));
    	if (newPosition!=this.position){
    		ab.setSelectedNavigationItem(newPosition);
    	}
    }
}